package cn.fancy.sdk.pay;

import static cn.fancy.sdk.utils.SpMmkvUtils.KEY_VERTICAL_ORIENTATION;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.fancy.sdk.baseview.DialogView;
import cn.fancy.sdk.common.utils.Logger;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.entity.DevBase.DevEnv;
import cn.fancy.sdk.pay.ali.AlipayView;
import cn.fancy.sdk.pay.entity.ChargeListsResultEntity;
import cn.fancy.sdk.pay.entity.CpPaymentEntity;
import cn.fancy.sdk.pay.entity.PayCallbackInfo;
import cn.fancy.sdk.pay.entity.PaymentId;
import cn.fancy.sdk.pay.utils.PayAdvertUpload;
import cn.fancy.sdk.pay.view.PayDetailView;
import cn.fancy.sdk.pay.view.PayListView;
import cn.fancy.sdk.pay.view.SuccessDialog;
import cn.fancy.sdk.pay.weixin.WeixinPayView;
import cn.fancy.sdk.utils.SpMmkvUtils;
import java.lang.reflect.Array;

public class GuildPayActivity extends Activity implements OnClickListener {
	
	public static final String EXTRA_SERVERID = "serverId";
	public static final String EXTRA_ROLEID = "roleId";
	public static final String EXTRA_PROPSID = "propsId";
	public static final String EXTRA_MONEY = "money";
	public static final String EXTRA_TYPE = "type";
	public static final String EXTRA_CHARGERESOURCE = "chargeSource";
	public static final String EXTRA_ITEM_DESC = "item_desc";
	public static final String EXTRA_ORDER = "order";
	public static final String EXTRA_CP_DATA = "cpdata";
	
	private Context mContext;
	
	/**
	 * 支付列表
	 */
	private LinearLayout leftLl;

	/**
	 * 支付输入框
	 */
	private LinearLayout rightLl;

	/**
	 * 等待框
	 */
	public Dialog dialog;

	/**
	 * CP传入参数
	 */
	public CpPaymentEntity cppayment;

	/**
	 * 回调CP接口
	 */
	private static QdPayCallback listener;

	/**
	 * 支付成功对话框
	 */
	SuccessDialog successDialog;

	/** 当前布局 **/
	protected ChargeAbstractView mCurrentView;

	/**
	 * 支付列表
	 */
	public ChargeListsResultEntity[] chargeLists;

	int type = Integer.MIN_VALUE;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		if(SpMmkvUtils.getValue(this, KEY_VERTICAL_ORIENTATION).equals(KEY_VERTICAL_ORIENTATION)){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			Log.w("GuildPayActivity", "GuildPayActivity setRequestedOrientation PORTRAIT");
		}
		mContext = this;
		
		cppayment = new CpPaymentEntity();
		Intent intent = getIntent();
		int money = intent.getIntExtra(EXTRA_MONEY, 0);
		cppayment.setMoney(money);
		cppayment.setTitleStr("充值");
		cppayment.setItem_desc(intent.getStringExtra(EXTRA_ITEM_DESC));
		cppayment.setExt(intent.getStringExtra(EXTRA_ORDER));
		cppayment.setPropsId(intent.getStringExtra(EXTRA_PROPSID));
		cppayment.setCpData(intent.getStringExtra(EXTRA_CP_DATA));

		type = intent.getIntExtra(EXTRA_TYPE, Integer.MIN_VALUE);

		addChargeLists();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 初始化支付activity界面
	 */
	private void initView() {
		setContentView(ResUtil.getLayoutId(mContext, "guild_pay_activity"));
		
		LinearLayout guildlogobarLl = (LinearLayout) this.findViewById(ResUtil.getId(
			mContext, "guild_logo_bar"));
		
		/*
		 * 标题
		 */
		TextView titleTv = (TextView) this.findViewById(ResUtil.getId(mContext, "guild_pay_title"));

		titleTv.setText(cppayment.getTitleStr());
		
		/*
		 * 返回键
		 */
		ImageView backIv = (ImageView) this.findViewById(ResUtil.getId(mContext,
			"guild_pay_back"));

		leftLl = (LinearLayout) this.findViewById(ResUtil.getId(mContext,
				"left"));

		rightLl = (LinearLayout) this.findViewById(ResUtil.getId(mContext,
				"right"));

		if (DevEnv.LOGO == 0) {
			guildlogobarLl.setVisibility(View.GONE);
		}

		backIv.setOnClickListener(this);
	}

	@Override
	public void onBackPressed() {
		this.finish();
	}

	/**
	 * 支付成功回调
	 */
	public void callback(final PayCallbackInfo callBack) {
		DialogView.cancelDialog(dialog);
		
		try {
			successDialog = new SuccessDialog(GuildPayActivity.this,
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						successDialog.cancel();
						if (listener != null) {
							listener.onPayFinish(callBack);
						}
						GuildPayActivity.this.finish();
					}
				});
			successDialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addChargeLists() {
		int size = 0;

		ChargeListsResultEntity alipayList = new ChargeListsResultEntity();
		alipayList.setPaymentId(PaymentId.ALIPAY_ID);
		alipayList.setPaymentName("支付宝");
		alipayList.setExt(cppayment.getExt());
		alipayList.setItem_desc(cppayment.getItem_desc());
		alipayList.setMoney(cppayment.getDiscountMoney(mContext));
		alipayList.setPropsId(cppayment.getPropsId());
		alipayList.setTitle(cppayment.getTitleStr());
		size++;
		
		ChargeListsResultEntity alipayScan = new ChargeListsResultEntity();
		alipayScan.setPaymentId(PaymentId.ALIPAY_SCAN_CODE);
		alipayScan.setPaymentName("支付宝扫码");
		alipayScan.setExt(cppayment.getExt());
		alipayScan.setItem_desc(cppayment.getItem_desc());
		alipayScan.setMoney(cppayment.getDiscountMoney(mContext));
		alipayScan.setPropsId(cppayment.getPropsId());
		alipayScan.setTitle(cppayment.getTitleStr());
		size++;
		
		ChargeListsResultEntity weixinList = new ChargeListsResultEntity();
		weixinList.setPaymentId(PaymentId.WEIXIN_ID);
		weixinList.setPaymentName("微信");
		weixinList.setExt(cppayment.getExt());
		weixinList.setItem_desc(cppayment.getItem_desc());
		weixinList.setMoney(cppayment.getDiscountMoney(mContext));
		weixinList.setPropsId(cppayment.getPropsId());
		weixinList.setTitle(cppayment.getTitleStr());
		size++;
		
		ChargeListsResultEntity wxScan = new ChargeListsResultEntity();
		wxScan.setPaymentId(PaymentId.WEIXIN_SCAN_CODE);
		wxScan.setPaymentName("微信扫码");
		wxScan.setExt(cppayment.getExt());
		wxScan.setItem_desc(cppayment.getItem_desc());
		wxScan.setMoney(cppayment.getDiscountMoney(mContext));
		wxScan.setPropsId(cppayment.getPropsId());
		wxScan.setTitle(cppayment.getTitleStr());
		size++;
		
		ChargeListsResultEntity[] cls = (ChargeListsResultEntity[]) Array.newInstance(ChargeListsResultEntity.class, size);
		for (int i = 0; i < size; i++) {
			if (alipayList != null) {
				cls[i] = alipayList;
				alipayList = null;
			} else if (alipayScan != null) {
				cls[i] = alipayScan;
				alipayScan = null;
			}else if (weixinList != null) {
				cls[i] = weixinList;
				weixinList = null;
			} else if (wxScan != null) {
				cls[i] = wxScan;
				wxScan = null;
			}
		}
		chargeLists = cls;

		initView();
		PayListView payListView = new PayListView(GuildPayActivity.this);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, -1);
		leftLl.addView(payListView.createView(), lp);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("wxpayresult", "wxpayresult");
		if (data == null) {
			return;
		}
		if(requestCode == 10) {
			GuildPayActivity.this.finish();
			return;
		} else if (requestCode == AlipayView.REQ_ALI && resultCode == RESULT_OK) {
			String money = data.getStringExtra(AlipayView.REQ_EXTRA_MONEY);
			PayCallbackInfo callback = new PayCallbackInfo();
			callback.statusCode = PayCallbackInfo.STATUS_SUCCESS;
			callback.money = Double.parseDouble(money);
			callback.desc = getResources().getString(
				ResUtil.getStringId(this, "guild_pay_success_des"));
			callback(callback);
			
			Logger.d("guildpay", "alipay success");
			
			return;
		}
		
		/*
		 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
		 */
		PayDetailView currentView = null;
		try {
			currentView = (PayDetailView) mCurrentView;
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Add Weixin Pay.
		if(currentView!=null){
			if (currentView instanceof WeixinPayView) {
				String str = data.getExtras().getString("resultCode");
				WeixinPayView weixinPayView = (cn.fancy.sdk.pay.weixin.WeixinPayView) currentView;
				weixinPayView.payResult(str);
			}
		}
	}

	public void replaceRight(ChargeAbstractView view) {
		mCurrentView = view;
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, -1);
		rightLl.removeAllViews();
		rightLl.addView(view.createView(), lp);
	}

	public static void start(Context context, String propsId, int money,
			String item_desc, String order, String cp_data, QdPayCallback sdklistener) {
		Intent intent = new Intent();
		listener = sdklistener;
		intent.putExtra(GuildPayActivity.EXTRA_PROPSID, TextUtils.isEmpty(propsId) ? "0" : propsId);
		intent.putExtra(GuildPayActivity.EXTRA_MONEY, money);
		intent.putExtra(GuildPayActivity.EXTRA_ITEM_DESC, item_desc);
		intent.putExtra(GuildPayActivity.EXTRA_ORDER, order);
		intent.putExtra(GuildPayActivity.EXTRA_CP_DATA, cp_data == null ? "" : cp_data);

		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setClass(context, GuildPayActivity.class);
		context.startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == ResUtil.getId(mContext, "guild_pay_back")) {
			this.onBackPressed();
		}
	}
	
}
